package com.calt.plm.basic.core.reader;

import java.io.IOException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import com.calt.plm.basic.core.annoation.BusinessEntity;
import com.calt.plm.basic.core.container.DataSourceContainer;
import com.calt.plm.basic.core.factory.EntityFactory;

/**
 * <p>类的简单描述</p>
 *
 * @author wuchao Create on 2022/9/22
 * @version 1.0
 */
public class EntityReader
{
	private static final Logger LOGGER = LoggerFactory.getLogger(EntityReader.class);

	private static final String ANNOTATION_NAME = BusinessEntity.class.getName();

	private ApplicationContext applicationContext;

	public void init(ApplicationContext applicationContext)
	{
		MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(applicationContext);
		String path = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(
				applicationContext.getEnvironment().resolvePlaceholders("com.calt")) + "/**/*.class";
		try
		{
			Resource[] resources = applicationContext.getResources(path);
			for (Resource resource : resources)
			{
				MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
				AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
				if(metadata.hasAnnotation(ANNOTATION_NAME))
				{
					Class<?> clazz = applicationContext.getClassLoader().loadClass(metadata.getClassName());
					BusinessEntity businessEntity = clazz.getAnnotation(BusinessEntity.class);
					String dataSourceName = businessEntity.dataSource();
					DataSource dataSource = DataSourceContainer.get(dataSourceName);
					if(null == dataSource)
					{
						LOGGER.error(dataSourceName + " is not exist,please check");
						throw new RuntimeException();
					}
					String name = businessEntity.name();
					EntityFactory.registerEntity(clazz, name, dataSource);
				}
			}
		}
		catch (IOException | ClassNotFoundException e)
		{
			LOGGER.debug("reader class error", e);
			throw new RuntimeException(e);
		}
	}
}
